<template>
    <div>
        <vab-card shadow="always">
            <template #default>
                <div class="flex_sb">
                    <div class="flex leve_title">
                        客户价目表-
                        <span class="remark_text">{{ _LeveTitle }}</span>
                    </div>
                    <div class="flex_just_end">
                        <el-button size="small" v-if="_IsSave" class="button_update" @click="_customerPriceCreate(2)">暂存</el-button>
                        <el-button size="small" @click="handleClick('back')">取消</el-button>
                        <el-button size="small" type="primary" @click="_customerPriceCreate(1)">提交</el-button>
                    </div>
                </div>
            </template>
        </vab-card>
        <!-- 基础信息 -->
        <BaseInfoForm
            :ref="(el) => baseInfoFormRef = el"
            :fromPage="fromPage"
            :screenObj="screenObj"
            @useOrgChange="useOrgChange"
            @checkUseOrg="checkUseOrg"
        />

        <!-- 产品价格明细-更新 -->
        <ProductPriceUpdate
            :isWarn="isWarn"
            v-if="fromPage == 'update'"
            @checkUseOrg="checkUseOrg"
            :ref="(el) => productPriceUpdateRef = el"

        />
        <!-- 产品价格明细-create -->
        <ProductPriceCreate
            v-else
            :isWarn="isWarn"
            @checkUseOrg="checkUseOrg"
            :ref="(el) => productPriceCreateRef = el"
        />

        <!-- 变更记录 -->
        <ChangeLog v-if="fromPage == 'update'" :ref="(el) => changeLogRef = el" />

    </div>
</template>

<script setup lang="ts">

defineOptions({
  name: 'PriceListCreate'
})

/**
 * @import
 */
import BaseInfoForm from './component/PriceOutside/BaseInfoForm.vue'
import ProductPriceCreate from './component/PriceOutside/ProductPriceCreate.vue'
import ProductPriceUpdate from './component/PriceOutside/ProductPriceUpdate.vue'

import ChangeLog from './component/PriceOutside/ChangeLog.vue'
import { customerPriceInfo, customerPriceSearch, customerPriceUpdate } from '~/src/api/dms/customer';
import { organization_list } from '~/src/api/dms/organization';

import { getCustomerPriceCreate } from '/@/api/dms/customer'
import { CloseNowTabs, DateFormat } from '~/src/utils/utils';
import { ElMessage } from 'element-plus';

import { _Message } from '~/src/utils/message'


/**
 * @var
 */
const router = useRouter()
const route = useRoute()
const { from } = route.query
let fromPage = ref<any>(from == 'toHandle' ? 'copy' : from)
let fromID = ref(route.query.id)

const baseInfoFormRef = ref()
const productPriceCreateRef = ref()
const productPriceUpdateRef = ref()
const changeLogRef = ref()
const userOrgId = ref('')

// 是否有错误提示
const isWarn = ref(false)


let screenObj = ref<any>(null)
/**
 * @method
 */

//  点击事件
const handleClick = async (value: any) => {
  if (value == 'back') {
    router.go(-1)
    return
  }
}

// 切换使用组织 清空数据
const useOrgChange = async (value: any) => {
  _GetProductSearch(value)
  if (productPriceCreateRef.value) {
    await productPriceCreateRef.value.resetData(value)
  }
}

// 校验是否选择使用组织
const checkUseOrg = () => {
  const { use_org_id } = baseInfoFormRef.value.baseForm
  if (!use_org_id) {
    _Message('请选择使用组织后再进行操作！', 'warning')
  }
}

// 筛选项
const _GetProductSearch = async (use_org_id = '') => {
  try {
    const res = await customerPriceSearch({ use_org_id })
    const resUse = await organization_list({})
    screenObj = await res.data
    screenObj.customer_list = await use_org_id ? screenObj.customer_list : []
    screenObj.use_org_id = await resUse.data
    // 组件获取筛选项
    baseInfoFormRef.value.getScreen(screenObj)

  } catch (error) { }
}

// 创建
const _customerPriceCreate = async (type: number) => {

  // 基本信息 校验
  const baseValidate = await baseInfoFormRef.value.baseFormRef.validate((valid: any) => {
    if (valid) return true
    return false
  })

  if (!baseValidate) return
  const baseForm = baseInfoFormRef.value.baseForm

  let productList: any = []
  let product_list: any = []

  if (fromPage.value == 'update') {
    productList = productPriceUpdateRef.value.productList
  } else {
    productList = productPriceCreateRef.value.productList
  }

  // 判空
  let VoidJudgment = false
  // 校验价格
  let VoidPrice = false

  if (productList.length) {
    // 判空
    VoidJudgment = productList.some((item: any) => {
      return !item.number || !item.name || item.price == null || (item.price.toString() == '')
    })

    VoidPrice = productList.every((item: any) => {
      return Number(item.price) >= Number(item.base_price)
    })
  }


  isWarn.value = false
  if (VoidJudgment) {
    _Message('请正确填写产品价格明细!', 'warning')
    isWarn.value = true
    return
  }
  if (!VoidPrice) {
    _Message('产品价格不能低于底价', 'warning')
    isWarn.value = true
    return
  }



  if (from == 'create') {
    product_list = productList.map((item: any) => {
      return {
        product_id: item.product_id,//产品ID --必填
        product_name: item.name,
        product_number: item.number,
        price: item.price || 0,//价格 --必填
        down_price: item.base_price || 0,//底价 --必填
        unit_id: item.unit_id || '',//基本单位id --必填
        batch_no: item.batch_no,//批次号
        forbid_status: item.forbid_status || 0, //是否失效
      }
    })
  } else {
    product_list = productList.map((item: any) => {
      return {
        product_id: item.product_id,//产品ID --必填
        product_name: item.name,
        product_number: item.number,
        price: item.price || 0,//价格 --必填
        down_price: item.base_price || 0,//底价 --必填
        unit_id: item.unit_id || '',//基本单位id --必填
        batch_no: item.batch_no,//批次号
        forbid_status: item.forbid_status || 0, //是否失效
        id: item.id || 0,
        expiry_date: DateFormat(item.expiry_date),
        effective_date: DateFormat(item.effective_date),
        status: item.status
      }
    })
  }

  let data: any = {
    name: baseForm.name,//价目表名称--必填
    use_org_id: baseForm.use_org_id, //使用组织--必填
    customer_id: baseForm.customer_id,//客户id --必填
    currency_id: baseForm.currency_id,//币别 --必填
    effective_date: DateFormat(baseForm.expiration_date[0]),//生效日 --必填
    expiry_date: DateFormat(baseForm.expiration_date[1]),//失效日 --必填
    is_included_tax: baseForm.is_included_tax,//是否含税 1含税0不含税 --必填
    remark: baseForm.remark,//备注
    type,//类型，1提交2暂存 --必填
    product_list: product_list || []//产品列表
  }

  if (from == 'copy') baseForm.id = ''

  const { id } = baseForm

  // 通过有无id判断
  if (id) {
    data.id = id
    customerPriceUpdate({ ...data }).then(async (res: any) => {
      ElMessage({ message: `提交成功`, type: 'success' })
      await CloseNowTabs(route.path, route, router)
      router.go(-1)
    }).catch(err => {
    })
  } else {
    getCustomerPriceCreate({ ...data }).then(async (res: any) => {
      ElMessage({ message: `${type == 1 ? '提交' : '暂存'}成功`, type: 'success' })
      await CloseNowTabs(route.path, route, router)
      router.go(-1)
    }).catch(err => {

    })
  }
}

// 获取更新数据
const _GetUpdateInfo = async () => {

  try {
    const res = await customerPriceInfo({ id: fromID.value })

    res.data.number = from == 'copy' ? '' : res.data.number
    baseInfoFormRef.value.getUpdateData({ ...res.data })

    const { use_org_id } = res.data

    // 通过使用组织 获取筛选项
    await _GetProductSearch(use_org_id)
    if (productPriceUpdateRef.value) productPriceUpdateRef.value.resetData(use_org_id)
    if (productPriceCreateRef.value) productPriceCreateRef.value.resetData(use_org_id)

    // 更新
    if (fromPage.value == 'update') {
      productPriceUpdateRef.value.getUpdateData(res.data)
      changeLogRef.value._getCustomerPriceLog(fromID.value)
    }
    // 复制
    if (fromPage.value == 'copy') {
      productPriceCreateRef.value.getUpdateData(res.data)
    }
  } catch (error) { }
}

/**
 * @实例
 */
// 标题显示
const _LeveTitle = computed(() => {
  if (from == 'create') return '创建中'
  if (from == 'toHandle') return '处理中'
  if (from == 'update') return '更新中'
  if (from == 'copy') return '创建中'
})
// 是否显示暂存
const _IsSave = computed(() => {
  if (from == 'update') return false
  return true
})

onMounted(() => {
  // 创建
  if (fromPage.value == 'create') _GetProductSearch()
  // 更新
  if (fromPage.value != 'create') _GetUpdateInfo()
})

</script>

<style scoped></style>
